package com.ligongmusic.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.ligongmusic.R;
import com.ligongmusic.util.GlobalParams;
import com.ligongmusic.util.JsonUtils;
import com.ligongmusic.util.LoggerUtils;
import com.ligongmusic.util.NetWorkUtils;
import com.ligongmusic.util.StorageUtils;
import com.ligongmusic.util.NetWorkUtils.NetWorkCallBack;
import com.ligongmusic.util.StringUtils;
import com.ligongmusic.view.TopManager;

@SuppressWarnings("deprecation")
public class ForgetPassWord extends Activity {
    private String code = "";
    private Button getCaptcha;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.forget_password);
        initView();
    }

    private void getCaptchaCode(String phone) {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("phone", phone));
        code = (int) ((Math.random() * 9 + 1) * 100000) + "";
        pairs.add(new BasicNameValuePair("smsCode", code));
        NetWorkUtils.getRequest(pairs, GlobalParams.GETCAPTCHA, new NetWorkCallBack() {
            @Override
            public void success(String result) {
                LoggerUtils.getLog(UserRegister.class).error(code);
            }

            @Override
            public void error() {
            }

            @Override
            public void error(String message) {
                LoggerUtils.getLog(UserRegister.class).error(message);
            }
        });
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what > 0)
                getCaptcha.setText(msg.what + "s后再次获取");
            if (msg.what == 0) {
                getCaptcha.setText("再次获取");
                getCaptcha.setClickable(true);
            }
        }
    };

    private void initView() {
        TopManager.getTopManager(ForgetPassWord.this).showTop(true, "忘记密码", new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        getCaptcha = (Button) findViewById(R.id.bt_get_captcha);
        getCaptcha.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                String phone = ((EditText) findViewById(R.id.et_user_phone)).getText().toString().trim();
                if (StringUtils.isEmpty(phone)) {
                    Toast.makeText(getApplicationContext(), "请输入手机号", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!StringUtils.isMobile(phone)) {
                    Toast.makeText(getApplicationContext(), "手机号不合法", Toast.LENGTH_SHORT).show();
                    return;
                }
                getCaptcha.setClickable(false);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 60; i >= 0; i--) {
                            Message.obtain(mHandler, i).sendToTarget();
                            SystemClock.sleep(1000);
                        }
                    }
                }).start();
                getCaptchaCode(phone);
            }
        });
        ((Button) findViewById(R.id.bt_submit)).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = ((EditText) findViewById(R.id.et_user_phone)).getText().toString().trim();
                if (StringUtils.isEmpty(phone)) {
                    Toast.makeText(getApplicationContext(), "请输入手机号", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!StringUtils.isMobile(phone)) {
                    Toast.makeText(getApplicationContext(), "手机号不合法", Toast.LENGTH_SHORT).show();
                    return;
                }
                String captcha = ((EditText) findViewById(R.id.et_captcha)).getText().toString().trim();
                if (StringUtils.isEmpty(captcha) || !code.equals(captcha)) {
                    Toast.makeText(getApplicationContext(), "验证码错误", Toast.LENGTH_SHORT).show();
                    return;
                }
                String passWord = ((EditText) findViewById(R.id.et_password)).getText().toString().trim();
                if (StringUtils.isEmpty(passWord)) {
                    Toast.makeText(getApplicationContext(), "请输入密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (passWord.length() < 6 || passWord.length() > 12) {
                    Toast.makeText(getApplicationContext(), "密码长度为6-12个字符", Toast.LENGTH_SHORT).show();
                    return;
                }
                submit(phone, passWord);
            }

        });
    }

    private void submit(final String phone, String passWord) {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("loginname", phone));
        pairs.add(new BasicNameValuePair("newpassword", passWord));
        NetWorkUtils.postRequest(pairs, GlobalParams.RESTART_PASSWORD, new NetWorkCallBack() {
            @Override
            public void success(String result) {
                LoggerUtils.getLog(ForgetPassWord.class).error(result);
                Toast.makeText(getApplicationContext(), JsonUtils.getString(result, "message"), Toast.LENGTH_SHORT).show();
                String code = JsonUtils.getString(result, "code");
                if ("200".equals(code)) {
                    // 保存修改成功后的用户名，将之前保存的密码清空
                    StorageUtils.getInstance(ForgetPassWord.this).writeString(GlobalParams.userNameKey, phone);
                    StorageUtils.getInstance(ForgetPassWord.this).writeString(phone, "");
                    finish();
                }
            }

            @Override
            public void error(String message) {
                // TODO Auto-generated method stub
            }

            @Override
            public void error() {
                // TODO Auto-generated method stub
            }
        });
    }
}
